/**
 * MACD拐点,底背离
 */
create or replace function getstmacd(days int) returns setof record as
$$
declare
rec record;
begin
  for rec in EXECUTE '
	select
	 b."date",b.volume,b.zf,b.macd,b.dz2,b.sdz,b.code,b."close",b."close"*0.99 as "推荐买入价",
	s."name"
	from basic_data b left join stocks s on b.code=s.code 
	where 
	to_date(b.date,''YYYY-MM-DD'') = getwd(current_date,'||days||')
	and strpos(s."name",''ST'')=0
	and b."close"*b.volume>200000--交易量大于一千万
	and b.macd != ''NaN'' and b.macd::float8 <= 0
	and b.macd::float8 > (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+1||') and code=b.code) 
	and (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+1||') and code=b.code) >= (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+2||') and code=b.code)
	and (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+2||') and code=b.code) < (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+3||') and code=b.code)
	and (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+3||') and code=b.code) < (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+4||') and code=b.code)
	and (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+4||') and code=b.code) < (select macd::float8 from basic_data where to_date(date,''YYYY-MM-DD'') = getwd(current_date,'||days+5||') and code=b.code)
	--and  to_date(date,''YYYY-MM-DD'') < getwd(current_date,'||days+4||') and code=b.code) <0
	order by b.macd::float8 
	;
' loop
    return next rec;
  end loop;
return;
end
$$
language 'plpgsql';